<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Exception\SessionValidException;
use App\Services\SessionService;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Context;
use Hyperf\Di\Annotation\Inject;

class WebUserAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $httpRequest;

    /**
     * @Inject
     * @var SessionService
     */
    protected $sessionService;

    public function __construct(ContainerInterface $container,RequestInterface $httpRequest)
    {
        $this->container = $container;
        $this->httpRequest = $httpRequest;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if($this->httpRequest->getPathInfo()!='/login'){
            if(!$this->sessionService->has('user')||!$this->sessionService->get('user',null)){
                throw new SessionValidException('还未登录', 401);
            }
        }
        $request = Context::set(ServerRequestInterface::class, $request->withAttribute('user', $this->sessionService->get('user')));
        return $handler->handle($request);
    }
}